package action.user;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import persistence.model.TdfkfaDeclareUnit;
import service.UnitService;

import com.opensymphony.xwork2.ActionSupport;

public class UnitManageAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = 8961717966621956225L;

    private HttpServletRequest request;

    private UnitService unitService;

    private String[] unitId;

    private String uid;

    private TdfkfaDeclareUnit unit;

    private String status;

    public String toEditUnit() throws Exception {
        if (unitId == null || unitId.length != 1) {
            return INPUT;
        } else {
            uid = unitId[0];
            request.getSession().setAttribute("uid", uid);
            return SUCCESS;
        }
    }

    public String prepareEditUnit() throws Exception {
        uid = (String) request.getSession().getAttribute("uid");
        unit = unitService.getUnit(new Integer(uid));

        if (unit == null) {
            return INPUT;
        }

        return SUCCESS;
    }

    public String modifyUnit() throws Exception {

        int r = unitService.updateUnit(unit);
        if (r == 1) {
            status = "success";
        } else {
            status = "failure";
        }
        return SUCCESS;
    }

    public String deleteUnit() throws Exception {

        if (unitId == null || unitId.length == 0) {
            return INPUT;
        }

        Integer[] ids = new Integer[unitId.length];
        for (int i = 0; i < unitId.length; i++) {
            ids[i] = new Integer(unitId[i]);
        }

        unitService.deleteUnit(ids);

        return SUCCESS;
    }

    public String[] getUnitId() {
        return unitId;
    }

    public void setUnitId(String[] unitId) {
        this.unitId = unitId;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public TdfkfaDeclareUnit getUnit() {
        return unit;
    }

    public void setUnit(TdfkfaDeclareUnit unit) {
        this.unit = unit;
    }

    public void setUnitService(UnitService unitService) {
        this.unitService = unitService;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String getStatus() {
        return status;
    }

}
